<?php

namespace app\admin\service;

use app\admin\model\ActionLog;
use support\Request;

class ActionLogService
{
    /**
     * 记录行为日志
     * @param Request $request
     * @param array $admin 管理员信息
     * @param bool $status 状态
     * @param array $response 响应数据
     * @param int|null $executionTime 执行时间(毫秒)
     * @return ActionLog
     */
    public function record(Request $request, array $admin, bool $status, array $response = [], ?int $executionTime = null): ActionLog
    {
        $log = new ActionLog();
        $log->admin_id = $admin['id'];
        $log->admin_name = $admin['user_name'];
        $log->url = trim($request->path());
        $log->ip = $request->getRealIp();
        $log->user_agent = $request->header('User-Agent');
        $log->request_data = json_encode($request->all(), JSON_UNESCAPED_UNICODE);
        $log->response_data = json_encode($response, JSON_UNESCAPED_UNICODE);
        $log->execution_time = $executionTime;
        $log->status = $status ? 1 : 0;
        $log->save();
        return $log;
    }

    /**
     * 获取日志列表
     * @param array $params 查询参数
     * @return array
     */
    public function getList(array $params): array
    {
        $query = ActionLog::query();
        // 添加查询条件
        if (!empty($params['admin_name'])) {
            $query->where('admin_name', 'like', '%' . $params['admin_name'] . '%');
        }
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }
        if (!empty($params['ip'])) {
            $query->where('ip', $params['ip']);
        }
        if (!empty($params['start_time'])) {
            $query->where('create_time', '>=', $params['start_time']);
        }
        if (!empty($params['end_time'])) {
            $query->where('create_time', '<=', $params['end_time']);
        }
        // 排序
        $query->orderBy('id', 'desc');
        // 分页
        $paginator = $query->paginate($params['limit'] ?? 10, ['*'], 'page', $params['page'] ?? 1);
        return [
            'page' => (int)($params['page'] ?? 1),
            'limit' => (int)($params['limit'] ?? 10),
            'count' => $paginator->total(),
            'list' => $paginator->items(),
        ];
    }

    /**
     * 获取日志详情
     * @param int $id 日志ID
     * @return ActionLog|null
     */
    public function getInfo(int $id): ?ActionLog
    {
        return ActionLog::find($id);
    }

    /**
     * 删除日志
     * @param int $id 日志ID
     * @return bool|null
     */
    public function delete(int $id): ?bool
    {
        $log = ActionLog::find($id);
        if (!$log) {
            return false;
        }
        return $log->delete();
    }

    /**
     * 批量删除日志
     * @param array $ids 日志ID数组
     * @return int
     */
    public function batchDelete(array $ids): int
    {
        return ActionLog::whereIn('id', $ids)->delete();
    }
}